#define _CRT_SECURE_NO_WARNINGS 1
class Solution {
public:
    string decodeString(string s) {
        stack<string> st;
        st.push("");
        stack<int> num;

        int i = 0, n = s.size();
        while (i < n) {
            if (isdigit(s[i])) {
                int tmp = 0;
                while (isdigit(s[i])) {
                    tmp = tmp * 10 + (s[i] - '0');
                    i++;
                }
                num.push(tmp);

            }
            else if (s[i] == '[')
            {
                i++;
                string str;
                while (isalpha(s[i]))
                {
                    str += s[i++];
                }
                st.push(str);
            }
            else if (s[i] == ']')
            {
                int x = num.top();
                num.pop();
                string str = st.top();
                st.pop();
                while (x--)
                {
                    st.top() += str;
                }
                i++;
            }
            else
            {
                while (i < n && isalpha(s[i]))
                {
                    st.top() += s[i];
                    i++;
                }
            }
        }
        return st.top();
    }
};